/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: iOS 权限测试页面 - 专门测试 iOS 平台权限处理的稳定性
 */

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '../services/ios_permission_helper.dart';
import '../services/permission_manager.dart';

/// iOS 权限测试页面
class IOSPermissionTestPage extends StatefulWidget {
  const IOSPermissionTestPage({super.key});

  @override
  State<IOSPermissionTestPage> createState() => _IOSPermissionTestPageState();
}

class _IOSPermissionTestPageState extends State<IOSPermissionTestPage> {
  bool _isLoading = false;
  String? _lastResult;
  Map<String, dynamic>? _iosReport;

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      _generateIOSReport();
    }
  }

  /// 生成 iOS 权限报告
  Future<void> _generateIOSReport() async {
    if (!Platform.isIOS) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final report =
          await IOSPermissionHelper.instance.generateIOSPermissionReport();
      if (mounted) {
        setState(() {
          _iosReport = report;
          _isLoading = false;
        });
      }
    } catch (error) {
      debugPrint('IOSPermissionTestPage: 生成报告失败 - $error');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 测试安全权限请求
  Future<void> _testSafePermissionRequest() async {
    setState(() {
      _isLoading = true;
      _lastResult = null;
    });

    try {
      final permissions = [Permission.notification];
      final results = await IOSPermissionHelper.instance
          .safeRequestPermissions(permissions);

      final grantedCount = results.values
          .where((status) => status == PermissionStatus.granted)
          .length;

      if (mounted) {
        setState(() {
          _lastResult = '安全权限请求完成：$grantedCount/${results.length} 个权限已授予';
          _isLoading = false;
        });
        await _generateIOSReport();
      }
    } catch (error) {
      debugPrint('IOSPermissionTestPage: 安全权限请求失败 - $error');
      if (mounted) {
        setState(() {
          _lastResult = '安全权限请求失败：$error';
          _isLoading = false;
        });
      }
    }
  }

  /// 测试 iOS 权限流程
  Future<void> _testIOSPermissionFlow() async {
    setState(() {
      _isLoading = true;
      _lastResult = null;
    });

    try {
      final permissions = [Permission.notification];
      final result = await IOSPermissionHelper.instance.handleIOSPermissionFlow(
        context,
        permissions,
      );

      if (mounted) {
        setState(() {
          _lastResult = 'iOS 权限流程完成：${result ? '成功' : '失败'}';
          _isLoading = false;
        });
        await _generateIOSReport();
      }
    } catch (error) {
      debugPrint('IOSPermissionTestPage: iOS权限流程失败 - $error');
      if (mounted) {
        setState(() {
          _lastResult = 'iOS 权限流程失败：$error';
          _isLoading = false;
        });
      }
    }
  }

  /// 测试传统权限请求（可能崩溃的方式）
  Future<void> _testTraditionalPermissionRequest() async {
    setState(() {
      _isLoading = true;
      _lastResult = null;
    });

    try {
      final result = await PermissionManager.instance.requestAudioPermissions();

      if (mounted) {
        setState(() {
          _lastResult = '传统权限请求完成：${result ? '成功' : '失败'}';
          _isLoading = false;
        });
        await _generateIOSReport();
      }
    } catch (error) {
      debugPrint('IOSPermissionTestPage: 传统权限请求失败 - $error');
      if (mounted) {
        setState(() {
          _lastResult = '传统权限请求失败：$error';
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('iOS 权限测试'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _generateIOSReport,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 平台检查
                  _buildPlatformSection(),
                  const SizedBox(height: 24),

                  // 测试结果
                  if (_lastResult != null) ...[
                    _buildResultSection(),
                    const SizedBox(height: 24),
                  ],

                  // 测试按钮
                  _buildTestSection(),
                  const SizedBox(height: 24),

                  // iOS 报告
                  if (_iosReport != null) _buildIOSReportSection(),
                ],
              ),
            ),
    );
  }

  /// 构建平台检查区域
  Widget _buildPlatformSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '平台信息',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Icon(
                  Platform.isIOS ? Icons.phone_iphone : Icons.android,
                  color: Platform.isIOS ? Colors.blue : Colors.green,
                ),
                const SizedBox(width: 8),
                Text(
                  '当前平台: ${Platform.operatingSystem}',
                  style: const TextStyle(fontWeight: FontWeight.w500),
                ),
              ],
            ),
            if (!Platform.isIOS) ...[
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '此测试页面专为 iOS 平台设计',
                  style: TextStyle(color: Colors.orange),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 构建测试结果区域
  Widget _buildResultSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '最近测试结果',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 12),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _lastResult!.contains('成功')
                    ? Colors.green.withOpacity(0.1)
                    : Colors.orange.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: _lastResult!.contains('成功')
                      ? Colors.green
                      : Colors.orange,
                ),
              ),
              child: Text(
                _lastResult!,
                style: TextStyle(
                  color: _lastResult!.contains('成功')
                      ? Colors.green[700]
                      : Colors.orange[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建测试区域
  Widget _buildTestSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '权限测试',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 16),

            // 安全权限请求测试
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: Platform.isIOS ? _testSafePermissionRequest : null,
                icon: const Icon(Icons.security),
                label: const Text('测试安全权限请求'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                ),
              ),
            ),

            const SizedBox(height: 8),

            // iOS 权限流程测试
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: Platform.isIOS ? _testIOSPermissionFlow : null,
                icon: const Icon(Icons.phone_iphone),
                label: const Text('测试 iOS 权限流程'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
              ),
            ),

            const SizedBox(height: 8),

            // 传统权限请求测试
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                onPressed: _testTraditionalPermissionRequest,
                icon: const Icon(Icons.warning),
                label: const Text('测试传统权限请求'),
                style: OutlinedButton.styleFrom(
                  foregroundColor: Colors.orange,
                ),
              ),
            ),

            const SizedBox(height: 12),

            // 说明文字
            Text(
              '• 安全权限请求：使用改进的 iOS 权限处理机制\n'
              '• iOS 权限流程：完整的用户体验流程\n'
              '• 传统权限请求：原始的权限请求方式（可能在 iOS 上不稳定）',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建 iOS 报告区域
  Widget _buildIOSReportSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'iOS 权限报告',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 16),

            // 基本信息
            Text(
              '平台: ${_iosReport!['platform']}',
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
            Text(
              '时间: ${_iosReport!['timestamp']}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),

            const SizedBox(height: 16),

            // 权限详情
            if (_iosReport!['permissions'] != null) ...[
              Text(
                '权限状态:',
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.w500,
                    ),
              ),
              const SizedBox(height: 8),
              ...(_iosReport!['permissions'] as Map<String, dynamic>)
                  .entries
                  .map((entry) {
                final permissionInfo = entry.value as Map<String, dynamic>;
                final isGranted =
                    permissionInfo['is_granted'] as bool? ?? false;
                final isSupported =
                    permissionInfo['is_supported'] as bool? ?? true;

                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Row(
                    children: [
                      Icon(
                        isGranted
                            ? Icons.check_circle
                            : isSupported
                                ? Icons.cancel
                                : Icons.help,
                        color: isGranted
                            ? Colors.green
                            : isSupported
                                ? Colors.orange
                                : Colors.grey,
                        size: 20,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              entry.key,
                              style:
                                  const TextStyle(fontWeight: FontWeight.w500),
                            ),
                            if (permissionInfo['explanation'] != null)
                              Text(
                                permissionInfo['explanation'],
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[600],
                                ),
                              ),
                          ],
                        ),
                      ),
                      Text(
                        isGranted
                            ? '已授予'
                            : isSupported
                                ? '未授予'
                                : '不支持',
                        style: TextStyle(
                          fontSize: 12,
                          color: isGranted
                              ? Colors.green
                              : isSupported
                                  ? Colors.orange
                                  : Colors.grey,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                );
              }),
            ],
          ],
        ),
      ),
    );
  }
}
